package com.chatroom.service.impl;

import com.chatroom.model.ChatRoom;
import com.chatroom.model.Message;
import com.chatroom.model.User;
import com.chatroom.repository.MessageRepository;
import com.chatroom.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class MessageServiceImpl implements MessageService {

    private final MessageRepository messageRepository;

    @Autowired
    public MessageServiceImpl(MessageRepository messageRepository) {
        this.messageRepository = messageRepository;
    }

    @Override
    public Message savePrivateMessage(String content, User sender, User receiver) {
        Message message = new Message();
        message.setContent(content);
        message.setSender(sender);
        message.setReceiver(receiver);
        message.setGroupMessage(false);
        return messageRepository.save(message);
    }

    @Override
    public Message saveGroupMessage(String content, User sender, ChatRoom chatRoom) {
        Message message = new Message();
        message.setContent(content);
        message.setSender(sender);
        message.setChatRoom(chatRoom);
        message.setGroupMessage(true);
        return messageRepository.save(message);
    }

    @Override
    public List<Message> getPrivateMessages(User user1, User user2) {
        List<Message> sentMessages = messageRepository.findBySenderAndReceiverOrderByTimestampAsc(user1, user2);
        List<Message> receivedMessages = messageRepository.findBySenderAndReceiverOrderByTimestampAsc(user2, user1);
        
        return Stream.concat(sentMessages.stream(), receivedMessages.stream())
                .sorted((m1, m2) -> m1.getTimestamp().compareTo(m2.getTimestamp()))
                .collect(Collectors.toList());
    }

    @Override
    public List<Message> getChatRoomMessages(ChatRoom chatRoom) {
        return messageRepository.findByChatRoomOrderByTimestampAsc(chatRoom);
    }
} 